package models

import (
	"gorm.io/gorm"
)

type Novel struct {
	gorm.Model
	Image   string
	Title   string
	Authors string
	Types   string
}

func (n *Novel) AddNovel() error {
	return DB.Create(&n).Error
}

func (n *Novel) ListNovels(keyword string, page, pageSize int) (listNovel []Novel, err error) {
	query := DB.Debug()
	if keyword != "" {
		query = query.Where("title like ? or authors like ? or types like ?",
			"%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
	}
	err = query.Scopes(Paginate(page, pageSize)).
		Find(&listNovel).Order("hot asc").Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type Shelf struct {
	gorm.Model
	UserId  int64
	NovelId int64
	Title   string
	Authors string
	Types   string
}

func (s *Shelf) AddShelf() error {
	return DB.Create(&s).Error
}
